import db from '../config/database.js';
import { uploadToCloudinary } from '../utils/cloudinaryUpload.js';

// Get store info
export const getStoreInfo = (req, res) => {
  try {
    const infoRows = db.prepare('SELECT * FROM store_info').all();
    
    const storeInfo = {};
    infoRows.forEach(row => {
      // Parse JSON values if they exist
      try {
        storeInfo[row.key] = JSON.parse(row.value);
      } catch {
        storeInfo[row.key] = row.value;
      }
    });

    res.json({
      success: true,
      data: storeInfo
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: error.message
    });
  }
};

// Update store info
export const updateStoreInfo = async (req, res) => {
  try {
    const updates = req.body;

    // Handle file uploads
    if (req.files) {
      if (req.files.logo) {
        const logoUrl = await uploadToCloudinary(req.files.logo[0].buffer, 'lucy-fashion/store');
        updates.logo = logoUrl;
      }
      if (req.files.banner) {
        const bannerUrl = await uploadToCloudinary(req.files.banner[0].buffer, 'lucy-fashion/store');
        updates.banner = bannerUrl;
      }
      if (req.files.wechat_qr) {
        const wechatUrl = await uploadToCloudinary(req.files.wechat_qr[0].buffer, 'lucy-fashion/store');
        updates.wechat_qr = wechatUrl;
      }
      if (req.files.store_images) {
        const uploadPromises = req.files.store_images.map(file => 
          uploadToCloudinary(file.buffer, 'lucy-fashion/store')
        );
        const imageUrls = await Promise.all(uploadPromises);
        updates.store_images = JSON.stringify(imageUrls);
      }
    }

    const stmt = db.prepare(`
      INSERT INTO store_info (key, value, updated_at)
      VALUES (?, ?, CURRENT_TIMESTAMP)
      ON CONFLICT(key) DO UPDATE SET value = ?, updated_at = CURRENT_TIMESTAMP
    `);

    for (const [key, value] of Object.entries(updates)) {
      const valueStr = typeof value === 'object' ? JSON.stringify(value) : String(value);
      stmt.run(key, valueStr, valueStr);
    }

    res.json({
      success: true,
      message: 'Store info updated successfully'
    });
  } catch (error) {
    console.error('Update store info error:', error);
    res.status(500).json({
      success: false,
      message: error.message
    });
  }
};

